package main

import (
	"errors"
	"time"

	"gitee.com/wu-jin-feng/fgin"
	"gitee.com/wu-jin-feng/fgin/demos/fmysql_test/dao"
	"github.com/gin-gonic/gin"
)

type User struct {
	Id int `form:"id" json:"id" binding:"required" msg:"id必填"`
}

func main() {

	f := fgin.Fgin{}
	r := f.GetHttpServer("./test.yaml")
	// 获得db
	db := f.GetGormDb("log_manager_db")
	redisClient1, _ := f.GetRedisClientByName("redisDB4")
	redisClient2, _ := f.GetRedisClientByName("redisDB5")
	r.GET("/get_user", func(ctx *gin.Context) {
		req := &User{}
		if err := fgin.FbindParams(ctx, req); err != nil {
			fgin.ReturnJson(ctx, 400, "", err)
			return
		}
		redisClient1.Set(ctx, "haha1", "success_haha1", 100*time.Second)
		redisClient2.Set(ctx, "haha2", "success", 100*time.Second)
		redisClient2.Del(ctx, "haha2")
		v := redisClient1.Get(ctx, "haha1").String()
		userDb := &dao.UserDao{}
		out, err := userDb.FindById(ctx.Request.Context(), db, req.Id)
		if err != nil {
			fgin.ReturnJson(ctx, 400, "", err)
			return
		}
		out, err = userDb.FindById(ctx.Request.Context(), db, req.Id)
		if err != nil {
			fgin.ReturnJson(ctx, 400, "", err)
			return
		}
		if out.Id == 0 {
			fgin.ReturnJson(ctx, 400, "", errors.New("没有该用户"))
			return
		}
		fgin.ReturnJson(ctx, 200, map[string]any{
			"out":     out,
			"redis_v": v,
		}, nil)
	})
	r.POST("/get_user", func(ctx *gin.Context) {
		req := &User{}
		if err := fgin.FbindParams(ctx, req); err != nil {
			fgin.ReturnJson(ctx, 400, "", err)
			return
		}
		userDb := &dao.UserDao{}
		out, err := userDb.FindById(ctx.Request.Context(), db, req.Id)
		if err != nil {
			fgin.ReturnJson(ctx, 400, "", err)
			return
		}
		if out.Id == 0 {
			fgin.ReturnJson(ctx, 400, "", errors.New("没有该用户"))
			return
		}
		fgin.ReturnJson(ctx, 200, out, nil)
	})
	f.Run(r)
}
